package com.obligatorio.persist.dao;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import org.apache.log4j.Logger;

import com.obligatorio.domain.Pais;

@Stateless
public class PaisDAOBean implements PaisDAOLocal {

	private static final Logger log = Logger.getLogger(PaisDAOBean.class
			.getName());

	@PersistenceContext(unitName = "JPA_UNIT_OBL")
	EntityManager em;

	@SuppressWarnings("unchecked")
	@Override
	public List<Pais> ObtenerTodoLosPaises() throws Exception {
		log.info("ObtenerTodoLosPaises()");
		try {
			List<Pais> res = (List<Pais>) em.createNamedQuery("findAllPais")
					.getResultList();
			log.info("Count Paises : "+res.size());
			return res;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Pais ObtenerUnPais(String name) throws Exception {
		log.info("Nombre pais> "+name);
		try {
			return (Pais) em.createNamedQuery("findPaisByName", Pais.class)
					.setParameter("Nombre", name).getSingleResult();
		} catch (NoResultException e) {
			log.error("No se encontraron resultados : "
					+ e.getMessage());
			return null;
		}
	}

	@Override
	public String getPrueba(String name) throws Exception {
		return "Hola Pais " + name + " !!!";
	}

	@Override
	public void insert(Pais p) throws Exception {

		System.out.println("Pais : " + p.toString());
		System.out.println("EM : " + em.toString());
		em.persist(p);

	}

}
